package com.hzlj.position.config.common.dto.common;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fz.common.base.exception.PubException;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lifh
 * @date 2023/5/9 11:45
 **/
public class LocateTimesDTO extends ArrayList<LocateTimesDTO.Item> {
    public LocateTimesDTO() {

    }

    public LocateTimesDTO(List<Item> items) {
        //去重
        items = new ArrayList<>(items.stream().collect(
                Collectors.toMap(Item::getId, e -> e, (e1, e2) -> e2)).values()
        );
        //排序
        items = CollectionUtil.sort(items, (a, b) -> {
            if (ObjectUtil.hasEmpty(a.getStartTime(), b.getStartTime())) {
                return 0;
            }
            return a.getStartTime().compareTo(b.getStartTime());
        });
        //添加数据
        this.addAll(items);
        //校验数据
        this.checkInTime();
    }

    /**
     * 检验
     * 1、参数是否正确
     * 2、是否用重复配置的时间段
     */
    public void checkInTime() {
        if (ObjectUtil.isEmpty(this)) {
            return;
        }
        for (Item locateTime : this) {
            if (ObjectUtil.isEmpty(locateTime.getStartTime())
                    || ObjectUtil.isEmpty(locateTime.getEndTime())) {
                throw new PubException("请同时设置开始时间、结束时间");
            }
            if (locateTime.getEndTime().compareTo(locateTime.getStartTime()) <= 0) {
                throw new PubException("结束时间必须大于开始时间");
            }
        }

        if (this.size() <= 1) {
            return;
        }
        //比较是否重复
        for (int i = 0; i < this.size() - 1; i++) {
            Item times1 = this.get(i);
            Item times2 = this.get(i + 1);
            if (times1.getEndTime().compareTo(times2.getStartTime()) >= 0) {
                throw new PubException(String.format("存在重复的时间段配置:[%s-%s]-[%s-%s]",
                        times1.getStartTime(), times1.getEndTime(), times2.getStartTime(), times2.getEndTime()));
            }
        }
    }

    @Data
    @NoArgsConstructor
    public static class Item {
        /**
         * id
         */
        private String id;
        /**
         * 开始时间:10:00
         */
        private String startTime;
        /**
         * 结束时间:12:00
         */
        private String endTime;

        public Item(String id, String startTime, String endTime) {
            this.id = id;
            this.startTime = startTime;
            this.endTime = endTime;
        }
    }
}
